package com.hxzy.commons.helper;

import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.hxzy.core.utils.UUIDGenerator;

/**
 * 上传文件辅助类
 * @author Abdi
 * @description 
 * @created Oct 15, 2013 3:47:15 PM
 */
public class UploadHelper {
	public static int SIZE_THRESHOLD = 4096;
	public static String TEMP_PATH = "/uploads";
	static{
		// TEMP_PATH初始化
	}
	
	/**
	 * 生成文件临时存放地址绝对路径
	 * 并检查路径
	 * @return
	 */
	public static String getTempFolderRealPath(HttpServletRequest request){
		Calendar calendar = Calendar.getInstance();
		String realPath = (request.getSession().getServletContext().
				getRealPath("/" + TEMP_PATH + "/") + "/" 
					+ calendar.get(Calendar.YEAR) + "/" 
						+ calendar.get(Calendar.MONTH) + "/" 
							+ calendar.get(Calendar.DATE) + "/" ) 
								.replace("\\", "/"); // "/" linux、window下皆可用
		File file = new File(realPath);
		if(!(file.exists())){
			file.mkdirs();
		}
		return realPath;
	}
	

	/**
	 * 获取上传文件列表
	 * @param request
	 * @param sizeThreshold
	 * @return
	 * @throws FileUploadException
	 */
	public static List<FileItem> getUploadFileList(HttpServletRequest request,int sizeThreshold) throws FileUploadException{
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(sizeThreshold);
		ServletFileUpload upload = new ServletFileUpload(factory);
		//upload.setSizeMax(6291456);
		upload.setHeaderEncoding("utf-8");
		
		List<FileItem> fileList = null;
		try {
		    fileList = upload.parseRequest(request);
		} catch (FileUploadException ex) {
			ex.printStackTrace();
			throw ex;
		}
		return fileList;
	}
	
	public static void main(String[] args) throws IOException {
		System.out.println(UUIDGenerator.getUUID());
	}
}
